package io.vertx.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dc.dcit.common.vo.UserVO;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.Json;
import io.vertx.example.feignService.UserFeignService;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

@Component
public class RestServer extends AbstractVerticle {
	@Autowired
	private UserFeignService userFeignService;

	@Autowired
	AppConfiguration configuration;

	/**
	 * This method is called when the verticle is deployed. It creates a HTTP
	 * server and registers a simple request handler.
	 * <p/>
	 * Notice the `listen` method. It passes a lambda checking the port binding
	 * result. When the HTTP server has been bound on the port, it call the
	 * `complete` method to inform that the starting has completed. Else it
	 * reports the error.
	 *
	 * @param fut
	 *            the future
	 */
	@Override
	public void start(Future<Void> fut) throws Exception {
		// Create a router object.
		final Router router = Router.router(vertx);

//		router.route().handler(BodyHandler.create());
		// router.get("/hello")表示所监听URL路径
/*		router.get("/").handler(new Handler<RoutingContext>() {

			public void handle(RoutingContext event) {
				event.response().putHeader("content-type", "text/html").end("Hello World");
			}
		});*/

		router.route("/findUserByName*").handler(BodyHandler.create());
		router.get("/findUserByName/:username").handler(this::findUserByName);

		vertx.createHttpServer().requestHandler(router::accept).listen(configuration.httpPort(), result -> {
			if (result.succeeded()) {
				fut.complete();
			} else {
				fut.fail(result.cause());
			}
		});
	}

	private void findUserByName(RoutingContext routingContext) {
		final String name = routingContext.request().getParam("username");
		if (name == null) {
			routingContext.response().setStatusCode(400).end();
		} else {
			final UserVO userVo= userFeignService.findUserByUsername(name);
			if (userVo == null) {
				routingContext.response().setStatusCode(404).end();
			} else {
				routingContext.response().putHeader("content-type", "application/json; charset=utf-8")
						.end(Json.encodePrettily(userVo));
			}

		}
	}
}
